package com.dhkj.circle.utils;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 该工具类主要负责字符串的处理，字符串转hex，或者中文转换的操作
 * <p>
 * 整理时间：2019-03-23
 */


public class StringUtils {

    // 将字符串编码成16进制数字,适用于所有字符（包括中文）
    private static String hexString = "0123456789ABCDEF";

    /*
     * 将字符串编码成16进制数字,适用于所有字符（包括中文）
     */
    public static String encode(String str) {
        //根据默认编码获取字节数组
        byte[] bytes = str.getBytes();
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        //将字节数组中每个字节拆解成2位16进制整数
        for (int i = 0; i < bytes.length; i++) {
            sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
            sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
        }
        return sb.toString();
    }

    //将16进制数字解码成字符串,适用于所有字符（包括中文）
    public static String decode(String bytes) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length() / 2);
        //将每2位16进制整数组装成一个字节
        for (int i = 0; i < bytes.length(); i += 2)
            baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString.indexOf(bytes.charAt(i + 1))));
        return new String(baos.toByteArray());
    }

    //转化十六进制编码为ASCll字符串
    public static String toStringHex(String s) {
        byte[] baKeyword = new byte[s.length() / 2]; //------------------
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "utf-8");//UTF-16le:Not
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    // 十六进制字符串转为byte数组
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    public static String bytesToHexString(byte bArray) {
        StringBuffer sb = new StringBuffer();
        String sTemp;

        sTemp = Integer.toHexString((0xFF) & (bArray));
        if (sTemp.length() < 2) {
            sb.append(0);
        }
        sb.append(sTemp.toUpperCase());

        return sb.toString();
    }

    public static byte[] HexToAscii(byte bValue) {
        byte[] bData = new byte[2];
        int iValue = bValue & 0xFF;

        bData[0] = (byte) (iValue / 16);
        bData[1] = (byte) (iValue % 16);

        if (bData[0] < 10) {
            bData[0] = (byte) (bData[0] + 0x30);
        } else {
            bData[0] = (byte) (bData[0] + 'A' - 10);
        }

        if (bData[1] < 10) {
            bData[1] = (byte) (bData[1] + 0x30);
        } else {
            bData[1] = (byte) (bData[1] + 'A' - 10);
        }
        return bData;
    }


    public static String listToString(List<String> list) {

        if (list == null) {
            return null;
        }

        StringBuilder result = new StringBuilder();
        boolean first = true;

        //第一个前面不拼接","
        for (String string : list) {
            if (first) {
                first = false;
            } else {
                result.append(",");
            }
            result.append(string);
        }
        return result.toString();
    }

    /**
     * 利用正则表达式判断字符串是否是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    public static byte AsciiToHex(byte bDataHigh, byte bDataLow) {
        int iValue = 0;

        if ((bDataHigh >= 0x30) && (bDataHigh <= 0x39)) {
            iValue = bDataHigh - 0x30;
        } else {
            iValue = bDataHigh - 'A' + 10;
        }
        iValue = iValue & 0x0F;
        iValue = iValue << 4;
        if ((bDataLow >= 0x30) && (bDataLow <= 0x39)) {
            iValue += bDataLow - 0x30;
        } else {
            iValue += bDataLow - 'A' + 10;
        }

        return (byte) iValue;
    }


    public static String getMatcher(String regex, String source) {
        String result = "";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(source);
        while (matcher.find()) {
            result = matcher.group(1);
        }
        return result;
    }

    public static HashMap<String, String> getForZF(String str2) {

        HashMap<String, String> map = new HashMap<>();
        while (str2.indexOf("=") > 0) {
            int i = str2.indexOf("=");
//            System.out.println(str2.substring(0, i));
            String ksy = str2.substring(0, i);
            str2 = str2.substring(++i);
            i = str2.indexOf("\\u003cbr\\u003e");
//            System.out.println(str2.substring(0, i));
            String value = str2.substring(0, i);
            str2 = str2.substring(i + 14);
            map.put(ksy, value);
        }
        return map;
    }

    public static HashMap<String, String> getForZF2(String str2) {

        HashMap<String, String> map = new HashMap<>();
        while (str2.indexOf("=") > 0) {
            int i = str2.indexOf("=");
//            System.out.println(str2.substring(0, i));
            String ksy = str2.substring(0, i);
            str2 = str2.substring(++i);
            i = str2.indexOf("<br>");
//            System.out.println(str2.substring(0, i));
            String value = str2.substring(0, i);
            str2 = str2.substring(i + 4);
            map.put(ksy, value);
        }
        return map;
    }

    /**
     * 不够位数的在前面补0，保留num的长度位数字
     *
     * @param code
     * @return
     */
    public static String autoGenericCode(String code, int num) {
        String result = "";
        // 保留num的位数
        // num 代表长度为4
        // d 代表参数为正数型
        result = String.format("%0" + num + "d", Integer.parseInt(code));
        return result;
    }

    public static String autoGenericCode2(String code, int num) {

        int count = code.length();
        while (num - count > 0) {
            code = "0" + code;
            count = code.length();
        }

//        String result = "";
//        // 保留num的位数
//        // num 代表长度为4
//        // d 代表参数为正数型
//        result = String.format("%0" + num + "c", code);
        return code;
    }

    public static String byte2hex(byte[] buffer) {
        String h = "";

        for (int i = 0; i < buffer.length; i++) {
            String temp = Integer.toHexString(buffer[i] & 0xFF);
            if (temp.length() == 1) {
                temp = "0" + temp;
            }
            h = h + " " + temp;
        }

        return h;

    }
}
